package helper

import (
	"gitee.com/lv_baobao/gcore/exceptions"
	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
)

type HttpResponseInfo struct {
	Content    interface{} `json:"content"`
	Message    string      `json:"message"`
	StatusCode int         `json:"statusCode"`
}

var instance *HttpResponseInfo

func GetHttpResponseInstance() *HttpResponseInfo {
	if instance == nil {
		instance = &HttpResponseInfo{} // <--- NOT THREAD SAFE
	}
	return instance
}

var jsonIterator = jsoniter.ConfigCompatibleWithStandardLibrary

func renderHttpJson(resInfo *HttpResponseInfo, c *gin.Context) {

	//c.Render(200, render.JSON{Data: resInfo})

	res, _ := jsonIterator.Marshal(resInfo)
	c.Writer.Header().Add("content-type", "application/json; charset=utf-8")
	c.Writer.Header().Add("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"")
	//c.Writer.Header().Add("Access-Control-Expose-Headers", "Date")
	// := strconv.Itoa(len(res))
	//c.Writer.Header().Add("Content-Length", lenStr)
	c.Writer.Write(res)
	c.Writer.Flush()
}

func (receiver HttpResponseInfo) InvalidParameter(c *gin.Context) {
	var resInfo = &(HttpResponseInfo{
		Content:    nil,
		StatusCode: 4,
		Message:    "无效的参数",
	})
	renderHttpJson(resInfo, c)
}

func (receiver HttpResponseInfo) Success(content interface{}, c *gin.Context) {
	var resInfo = &(HttpResponseInfo{
		Content:    content,
		StatusCode: 0,
		Message:    "",
	})
	renderHttpJson(resInfo, c)
}

func (receiver HttpResponseInfo) Error(msg interface{}, c *gin.Context) {
	errStr := errorToString(msg)
	var resInfo = &(HttpResponseInfo{
		Content:    nil,
		StatusCode: 6,
		Message:    errStr,
	})
	renderHttpJson(resInfo, c)
}

// recover错误，转string
func errorToString(r interface{}) string {
	switch v := r.(type) {
	case exceptions.BusinessException:
		return v.Message
	case error:
		return "系统发送异常"
	default:
		return r.(string)
	}
}

func (receiver HttpResponseInfo) SessionInValid(c *gin.Context) {
	var resInfo = &(HttpResponseInfo{
		Content:    "回话过期",
		StatusCode: 2,
		Message:    "回话过期",
	})
	renderHttpJson(resInfo, c)
}
